<?php

namespace App\Http\Controllers\Home;

use App\Helpers\ArticlePoster;
use App\Model\Article;
use App\Model\Visit;
use Illuminate\Http\Request;

class ArticleController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        $query = Article::with('covers','userHasCollect')->where('column_id','<>',1)
            ->where('state','=','publish')
            ->where('online','=','yes');

        if ($column_id = $request->input('column')){
            $query->where('column_id','=',$column_id);
        }
        if ($exclude_id = $request->input('exclude_id')){
            $query->where('id','<>',$exclude_id);
        }

        $query = $query->select('id',
            'title',
            'column_id',
            'abstract',
            'type',
            'video_path',
            'video_type',
            'feature',
            'created_at',
            'updated_at');

        $items = $query->orderBy('weight','desc')
            ->orderBy('created_at','desc')
            ->paginate(15);

        return $this->success($items);
    }



    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $item = Article::with('covers','user','userHasCollect')->find($id);

        if ($item){
            $this->visit($id,1,$item);

            return $this->success($item);
        }

        return $this->notFond();
    }

    public function poster(Request $request,$id)
    {
        $username = $request->input('username');
        if (!$username){
            $username = $this->loginUser()->name;
        }
        $ProductPoster = new  ArticlePoster();
        $path = $ProductPoster->create($id,$this->loginUserId(),$username);
        if ($path) {
            return $this->success($path);
        }
        return false;
    }
}
